#pragma once
#include <string>
#include <functional>

#include <pthread.h>
#include <cassert>
using namespace std;


class Thread
{
    using func_t = function<void*(void*)>;
public:
    //必须是静态成员函数,因为必须只有一个参数
    static void* start_routine(void* args) 
    {
        Thread* td = static_cast<Thread*>(args);
        return td->callback();
    }

    Thread()
    {
        char buffer[1024];
        snprintf(buffer,sizeof buffer,"%thread->%d",_threadnum++);
        _name = buffer;
    }

    void start(func_t fun, void* args = nullptr)
    {
        _fun = fun;
        _args = args;
        int n = pthread_create(&_tid,nullptr,start_routine,this);
        assert(n == 0);
        (void)n;
    }
    
    void join()
    {
        int n = pthread_join(_tid,nullptr);
        assert(n == 0);
        (void)n;
    }

    void* callback()
    {
        return _fun(_args);
    }

    string to_threadname()
    {
        return _name;
    }


private:
    string _name;
    func_t _fun;
    void* _args;
    pthread_t _tid;

    static int _threadnum;
};

int Thread::_threadnum = 1;